/**
 *
 */
package com.elcom.emocbc.cbm;

import java.io.IOException;
import java.net.SocketTimeoutException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.elcom.ipc_udp_msg.CONVERT;
import com.elcom.ipc_udp_msg.MSG_DEFINE;
import com.elcom.ipc_udp_msg.MessageAnalyzerImpl;
import com.elcom.ipc_udp_msg.control.MSG_GET_MODULE_INFO;
import com.elcom.ipc_udp_msg.control.MSG_GET_MODULE_INFO_RESP;
import com.elcom.ipc_udp_msg.control.MSG_RELOAD_CONFIG;
import com.elcom.ipc_udp_msg.control.MSG_RELOAD_CONFIG_RESP;
import com.elcom.emocbc.util.ActionThread;
import com.elcom.util.ipc.IPCHandler;
import com.elcom.util.ipc.message.MESSAGE;

/**
 * @author tiamo114
 *
 */
public class MonitorThread extends ActionThread {

    private final Log LOG = LogFactory.getLog(MonitorThread.class);
    private IPCHandler ipc = null;
    private String NAME_IPC_HANDLER = "cellbroadcast";

    /**
     * @param name
     */
    public MonitorThread(String name, String ipcName) {
        super(name);
        this.NAME_IPC_HANDLER = ipcName;
        try {
            this.ipc = new IPCHandler(new MessageAnalyzerImpl(), NAME_IPC_HANDLER);
        } catch (IOException e) {
            LOG.error("Exception init IPCHandler: ", e);
        }
    }

    /*
     * (non-Javadoc)
     *
     * @see com.elcom.livescreen.util.ActionThread#action()
     */
    @Override
    protected void action() throws Exception {
        try {
            MESSAGE ipc_msg = ipc.getMessage();
            if (null != ipc_msg) {
                if (ipc_msg instanceof MSG_RELOAD_CONFIG) {
                    LOG.info("Starting reload config system====================");
                    CellBroadcastService.reLoadConfig();
                    MSG_RELOAD_CONFIG req = MSG_RELOAD_CONFIG.class.cast(ipc_msg);
                    MSG_RELOAD_CONFIG_RESP resp = (MSG_RELOAD_CONFIG_RESP) ipc.createResponse(req);
                    resp = (MSG_RELOAD_CONFIG_RESP) CONVERT.assign_req_to_resp(req, resp);
                    String send_module = CONVERT.getSourceModule(req);
                    resp.RESPONSE_CODE = MSG_DEFINE.RESPONSE_CODE.E_OK;
                    try {
                        ipc.sentMessage(send_module, resp);
                        LOG.info("Sent -- " + resp);
                    } catch (Throwable t) {
                        LOG.error("[!!!SEND!!!]", t);
                    }
                    LOG.info("Completed reload config system====================");
                } else if (ipc_msg instanceof MSG_GET_MODULE_INFO) {
                    on_module_info(MSG_GET_MODULE_INFO.class.cast(ipc_msg));
                } else {
                    LOG.info(new StringBuilder("System not support errorCode: ").append(ipc_msg.toString()).append("====================").toString());
                }
            }
        } catch (SocketTimeoutException e) {
            //Do nothing
        } catch (Exception ex) {
            LOG.error("Exception when get IPC message and execute: ", ex);
        }
    }

    private void on_module_info(MSG_GET_MODULE_INFO req) {
        try {
            MSG_GET_MODULE_INFO_RESP resp = (MSG_GET_MODULE_INFO_RESP) ipc.createResponse(req);
            resp = (MSG_GET_MODULE_INFO_RESP) CONVERT.assign_req_to_resp(req, resp);
            String send_module = CONVERT.getSourceModule(req);

            try {
                resp.RESPONSE_CODE = MSG_DEFINE.RESPONSE_CODE.E_OK;
                resp.MODULE_INFO = new String[]{get_module_info()};
            } catch (Throwable t) {
                resp.RESPONSE_CODE = MSG_DEFINE.RESPONSE_CODE.E_UNKNOWN;
            }
            try {
                ipc.sentMessage(send_module, resp);
                LOG.info("Sent -- " + resp);
            } catch (Throwable t) {
                LOG.error("[!!!SEND!!!]", t);
            }

        } catch (Throwable t) {
            LOG.error("Unexpected throwable", t);
        }
    }

    private String get_module_info() {
        String totalmem = Runtime.getRuntime().totalMemory() + "";
        String maxmem = Runtime.getRuntime().maxMemory() + "";
        String freemem = Runtime.getRuntime().freeMemory() + "";
        int threads = Thread.currentThread().getThreadGroup().activeCount();

        String rs = "Memory monitor: Total = " + totalmem + "| Max = " + maxmem + "| Free = " + freemem + "| Threads: " + threads;

        return rs;
    }

    /*
     * (non-Javadoc)
     *
     * @see
     * com.elcom.livescreen.util.ActionThread#onException(java.lang.Exception)
     */
    @Override
    protected void onException(Exception e) {
        LOG.info(this.getName() + " is onException: " + e.getMessage());
    }

    /*
     * (non-Javadoc)
     *
     * @see com.elcom.livescreen.util.ActionThread#onExecuting()
     */
    @Override
    protected void onExecuting() throws Exception {
        LOG.info(this.getName() + " is onExecuting");
    }

    /*
     * (non-Javadoc)
     *
     * @see com.elcom.livescreen.util.ActionThread#onKilling()
     */
    @Override
    protected void onKilling() {
        LOG.info(this.getName() + " is onKilling");
    }

    /*
     * (non-Javadoc)
     *
     * @see com.elcom.livescreen.util.ActionThread#sleeptime()
     */
    @Override
    protected long sleeptime() throws Exception {
        return 1;
    }
}
